package com.jsjosem.aftersales.ui.login;

import static com.jsjosem.aftersales.constant.CommonConstant.LOGIN_USER;
import static com.jsjosem.aftersales.constant.CommonConstant.USER_INFO;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.UserApi;
import com.jsjosem.aftersales.cache.UserCache;
import com.jsjosem.aftersales.data.request.LoginParam;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.LoggedInUser;
import com.jsjosem.aftersales.data.response.LoginResponse;
import com.jsjosem.aftersales.data.response.LoginUserResponse;
import com.jsjosem.aftersales.databinding.ActivityLoginBinding;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.ui.MainActivity;
import com.jsjosem.aftersales.utils.ImmUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.Objects;

import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * 登录界面
 */
public class LoginActivity extends AppCompatActivity {

    private Retrofit retrofit;

    private ActivityLoginBinding binding;

    private SharedPreferences sp;

    private LoggedInUser loggedInUser;

    private EditText accountEdit;

    private EditText passwordEdit;

    private UserCache userCache;

    private Dialog loadingDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    /**
     * 初始化页面
     */
    private void initView() {
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        accountEdit = findViewById(R.id.account);
        passwordEdit = findViewById(R.id.password);
        retrofit = RetrofitClient.getInstance();
        ImmUtils.setEditTextHintFontSize(accountEdit, 12,"请输入账号" );
        ImmUtils.setEditTextHintFontSize(passwordEdit, 12,"请输入密码" );
        // 登录用户信息不为空，回填account和password
        if (Objects.nonNull(loggedInUser)) {
            accountEdit.setText(loggedInUser.getAccount());
            passwordEdit.setText(loggedInUser.getPassword());
        }

        // 点击注册账号
        click(R.id.register, RegisterAccountActivity.class);

        // 点击忘记密码
        click(R.id.forgot_password, ForgotPasswordActivity.class);

        // 点击登录
        clickLogin();

    }

    /**
     * 点击按钮并启动新页面
     *
     * @param id
     * @param clz
     */
    private void click(int id, Class<?> clz) {
        TextView registerTv = findViewById(id);
        registerTv.setOnClickListener(view -> {
            Intent intent = new Intent(LoginActivity.this, clz);
            startActivity(intent);
        });
    }

    /**
     * 点击登录
     */
    private void clickLogin() {
        Button loginBt = findViewById(R.id.login_bt);
        loginBt.setOnClickListener(view -> {
            if (accountEdit.getText().length() <= 0) {
                accountEdit.setError("账号不能为空");
                return;
            }
            if (passwordEdit.getText().length() <= 0) {
                passwordEdit.setError("密码不能为空");
                return;
            }
            String username = accountEdit.getText().toString();
            String password = passwordEdit.getText().toString();

            // 点击登录后隐藏输入法
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);
            loadingShow();
            LoginParam loginParam = new LoginParam();
            loginParam.setUsername(username);
            loginParam.setPassword(password);
            UserApi userApi = retrofit.create(UserApi.class);
            Call<BaseResponse<LoginResponse>> login = userApi.login(loginParam);
            AsyncRequest<BaseResponse<LoginResponse>> requestLogin = new AsyncRequest<>();
            requestLogin.sendRequest(login, (res) -> {
                userCache = UserCache.getInstance();
                userCache.setToken(res.getData().getmAccessToken());
                userCache.login();
                loggedInUser = new LoggedInUser();
                loggedInUser.setAccess_token(res.getData().getmAccessToken());
                // 登录成功获取当前登录用户信息
                Call<BaseResponse<LoginUserResponse>> loginUserInfo = userApi.getLoginUserInfo();
                AsyncRequest<BaseResponse<LoginUserResponse>> getLoginUserReq = new AsyncRequest<>();
                getLoginUserReq.sendRequest(loginUserInfo, (userRes) -> {
                    LoginUserResponse data = userRes.getData();
                    loggedInUser.setAccount(username);
                    loggedInUser.setEmail(data.getmEmail());
                    loggedInUser.setPassword(password);
                    loggedInUser.setExpired_at(data.getmExpiredTime());
                    loggedInUser.setId(data.getmId());
                    loggedInUser.setName(data.getmRealname());
                    loggedInUser.setTelephone(data.getmMobile());
                    loggedInUser.setAvatar(data.getmAvatar());
                    loggedInUser.setDepartment(data.getmDeptName());
                    loggedInUser.setDepartmentId(data.getmDeptId());
                    userCache.setUser(loggedInUser);
                    // 保存用户的账户信息
                    sp = getSharedPreferences(USER_INFO, Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString(LOGIN_USER, new Gson().toJson(userCache));
                    edit.apply();
                    loadingDialog.dismiss();
                    // 启动主页面
                    startMainActivity();
                }, failedMessage -> Toast.makeText(LoginActivity.this, failedMessage.toString(), Toast.LENGTH_SHORT).show());
            }, failedMessage -> {
                loadingDialog.dismiss();
                Toast.makeText(LoginActivity.this, failedMessage.toString(), Toast.LENGTH_SHORT).show();
            });
        });
    }

    /**
     * 只有登陆以后才可以启动主页
     */
    private void startMainActivity() {
        // 启动主页之前先缓存用户信息
        userCache.setUser(loggedInUser);
        // 启动主页面
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void loadingShow() {
        loadingDialog = new Dialog(this, R.style.normal_dialog_style);
        View loadingView = View.inflate(this, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }
}